package com.spring.security.project.controller;

import com.google.code.kaptcha.Producer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

@RestController
@Slf4j
public class CaptchaController {
    @Autowired
    private Producer producer;

    @GetMapping(value = "/captcha.jpg")
    public void getCaptche(HttpServletRequest request,
                           HttpServletResponse response) throws IOException {
        response.setContentType("image/jpeg");
        //创建验证码文本
        String text = producer.createText();
        log.info("获取的文本信息：{}",text);
        request.getSession().setAttribute("captcha",text);
        BufferedImage image = producer.createImage(text);
        ServletOutputStream outputStream = response.getOutputStream();
        ImageIO.write(image,"jpg",outputStream);
        try {
            outputStream.flush();
        } finally {
            outputStream.close();
        }
    }
}
